from sqlalchemy import Column,Integer,String,func
from random import randint

from db_util import Base,engine,Session

class Item(Base):
    __tablename__ = 't_item'
    id = Column(Integer,primary_key=True,autoincrement=True)
    title = Column(String(32))
    price = Column(Integer)

def create_data():
    with Session() as session:
        for i in range(10):
            item = Item(title=f'产品{i+1}',price=randint(1,100))
            session.add(item)
        session.commit()

def query_model_name():
    #获取所有字段
    with Session() as session:
        rs = session.query(Item).all()
        for r in rs:
            print(r.title)

def query_model_str():
    #获取指定字段
    with Session() as session:
        rs = session.query(Item.title,Item.price).all()
        for r in rs:
            print(r.price)

def query_func():
    with Session() as session:
        rs = session.query(func.count(Item.id)).first()
        print(rs)

if __name__ == '__main__':
    # Base.metadata.create_all(engine)
    # create_data()
    query_model_name()